package com.mrzhou.log.error;

import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.api.ResultCode;
import com.mrzhou.log.publisher.ErrorLogPublisher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.annotation.Nullable;
import java.util.Map;

@Slf4j
public class CloudErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        String requestUri = this.getAttr(webRequest, "javax.servlet.error.request_uri");
        Integer status = this.getAttr(webRequest, "javax.servlet.error.status_code");
        Throwable throwable = getError(webRequest);
        R result;
        if (throwable == null) {
            R.fail(ResultCode.FAILURE, "系统未知异常[HttpStatus]: " + status);
            result = R.fail(ResultCode.FAILURE, "系统未知异常[HttpStatus]: " + status);
        } else {
            log.error(String.format("URL:%s error status:%d", requestUri, status), throwable);
            result =R.fail(status, throwable.getMessage());
        }
        ErrorLogPublisher.publisherEvent(throwable, requestUri);
        return super.getErrorAttributes(webRequest, includeStackTrace);
    }

    @Nullable
    private <T> T getAttr(WebRequest webRequest, String key) {
        return (T) webRequest.getAttribute(key, RequestAttributes.SCOPE_REQUEST) ;
    }

}
